#include "App.h"
#include <QFile>
#include <QWindow>
#include <QFontDatabase>
#include <QInputMethodEvent>
#include <QLineEdit>
#include "xyskin.h"
#include "xyvirtualkeyboard.h"
#include <QDebug>
#include <QTranslator>
QTranslator *m_translator = nullptr;
void changCurrentLanguage(int index) {
    qDebug()<<"changCurrentLanguage"<<index<<"start";
    QString path;
    QFile file("/home/root/lan.data");

    if(index<=0)return;
    else {
        bool ret = file.open(QIODevice::WriteOnly);
        if(ret) {
            QDataStream in(&file);
            in<<index;
            file.close();
        }
    }

    if(m_translator) {
        qApp->removeTranslator(m_translator);
        delete m_translator;
        m_translator = nullptr;
    }

    switch (index) {
        case 1:
                break;
        case 2:
                path = ":/translate/translate/tspm160_En.qm";
                break;
        case 3:
                break;
        default:
            break;
    }

    if(!path.isEmpty()) {
         m_translator = new QTranslator(qApp);
    }

    if(m_translator)
    if(m_translator->load(path)){
         qApp->installTranslator(m_translator);
    }else {
        delete m_translator;
        m_translator = nullptr;
    }
    qDebug()<<"changCurrentLanguage"<<index<<"end";
}

App::App(int &argc, char **argv)
    : QApplication{ argc, argv }
{

    /* install font */
    int wqy_font_id  = QFontDatabase::addApplicationFont(":/fonts/fonts/wqy.ttf");
    QString wqy_font = QFontDatabase::applicationFontFamilies(wqy_font_id).at(0);
    setFont(QFont(wqy_font));
}



void App::bindingInputMethod()
{
    QObject::connect(inputMethod(), &QInputMethod::cursorRectangleChanged,
                     XYVirtualKeyboard::getInstance(), [](){
        QWindow *window = focusWindow();
        QWidget* widget = focusWidget();
        if(widget && dynamic_cast<QLineEdit*>(widget))
        {
            if (window && widget && !XYVirtualKeyboard::getInstance()->isVisible()) {
                QRect rect = inputMethod()->anchorRectangle().toRect().translated(window->position());


                QLineEdit* lineEdit = (QLineEdit*)widget;
                if((lineEdit->echoMode() == QLineEdit::PasswordEchoOnEdit)
                        || (lineEdit->echoMode() == QLineEdit::Password))
                {
                    XYVirtualKeyboard::getInstance()->switchToChinese(false);
                    XYVirtualKeyboard::getInstance()->lockLanguage(true);
                }
                else
                {
                    XYVirtualKeyboard::getInstance()->lockLanguage(false);
                }

                QPoint targetPos = rect.bottomLeft() + QPoint(0, 20);
                targetPos.setX(200);
                if(targetPos.y() >= 500)
                {
                    targetPos.setY(qMax(targetPos.y() - 500, 0));
                }

                //XYVirtualKeyboard::getInstance()->move(targetPos - QPoint(0, delta)/*rect.bottomLeft() + QPoint(0, 5)*/);
                XYVirtualKeyboard::getInstance()->move(targetPos);
                XYVirtualKeyboard::getInstance()->show();
            }
        }
        else
        {
            XYVirtualKeyboard::getInstance()->hide();
        }

    });

    QObject::connect(this, &QApplication::focusChanged,
                     XYVirtualKeyboard::getInstance(), [](QWidget *old, QWidget *now){
        QWindow *window = focusWindow();
        if(window && now && dynamic_cast<QLineEdit*>(now))
        {
            QRect destRect = inputMethod()->anchorRectangle().toRect().translated(window->position());
            QPoint destPos = destRect.bottomLeft() + QPoint(0, 20);
            QPoint currentPos = XYVirtualKeyboard::getInstance()->pos();
            bool moved = ((destPos.x() != currentPos.x()) || (destPos.y() != currentPos.y()));
            bool hided = !XYVirtualKeyboard::getInstance()->isVisible();
            if (moved || hided) {

                QLineEdit* lineEdit = (QLineEdit*)now;
                if((lineEdit->echoMode() == QLineEdit::PasswordEchoOnEdit)
                        || (lineEdit->echoMode() == QLineEdit::Password))
                {
                    XYVirtualKeyboard::getInstance()->switchToChinese(false);
                    XYVirtualKeyboard::getInstance()->lockLanguage(true);
                }
                else
                {
                    XYVirtualKeyboard::getInstance()->lockLanguage(false);
                }

                destPos.setX(200);
                if(destPos.y() >= 500)
                {
                    destPos.setY(qMax(destPos.y() - 500, 0));
                }

                XYVirtualKeyboard::getInstance()->move(destPos);
                XYVirtualKeyboard::getInstance()->show();
            }
        }
        else
        {
            XYVirtualKeyboard::getInstance()->hide();
        }

    });

    QObject::connect(XYVirtualKeyboard::getInstance(),
                     &XYVirtualKeyboard::send_preedit, [](const QString &text){
        QInputMethodEvent *event =
                new QInputMethodEvent(text, QList<QInputMethodEvent::Attribute>());

        QWidget *focusWindow = focusWidget();
        if (focusWindow) {
            postEvent(focusWindow, event);
        }
    });
    QObject::connect(XYVirtualKeyboard::getInstance(),
                     &XYVirtualKeyboard::send_commit, [](const QString &text){
        QInputMethodEvent *event = new QInputMethodEvent;
        event->setCommitString(text);
        QWidget *focusWindow = focusWidget();
        if (focusWindow) {
            postEvent(focusWindow, event);
        }
    });

    QObject::connect(XYVirtualKeyboard::getInstance(),
                     &XYVirtualKeyboard::keyClicked, [](int unicode, int key, Qt::KeyboardModifiers modifiers, bool press){
        QKeyEvent *event = new QKeyEvent(press ? QEvent::KeyPress : QEvent::KeyRelease,
                                         key,
                                         modifiers,
                                         QChar(unicode));

        QWidget *focusWindow = focusWidget();
        if (focusWindow) {
            postEvent(focusWindow, event);
        }
    });
}
